class WebSocketManager {
    constructor(url) {
        this.url = url; // WebSocket URL
        this.socketTask = null; // 每个实例独立的 WebSocket 任务
        this.isConnected = false; // 当前 WebSocket 是否已连接
        this.listeners = []; // 消息监听器
    }

    /**
     * 建立 WebSocket 连接
     * @param {Array} subscriptions - 订阅的主题
     */
    connect(subscriptions = []) {
        if (this.isConnected) {
            console.warn('WebSocket is already connected.');
            return;
        }

        this.socketTask = uni.connectSocket({
            url: this.url,
            success: () => {
                console.log('WebSocket connection created.');
            },
            fail: (err) => {
                console.error('WebSocket connection failed:', err);
            },
        });

        // 监听打开事件
        this.socketTask.onOpen(() => {
            console.log('WebSocket connection established.');
            this.isConnected = true;

            // 订阅主题
            if (subscriptions.length > 0) {
                const subscribeMessage = JSON.stringify({
                    req: subscriptions,
                    sub: subscriptions,
                });
                this.send(subscribeMessage);
            }
        });

        // 监听消息事件
        this.socketTask.onMessage((res) => {
            try {
                const arrayBuffer = new Uint8Array(res.data);
                const decompressed = pako.inflate(arrayBuffer, {
                    to: 'string',
                });
                const json = JSON.parse(decompressed);

                if (json.ping) {
                    // 响应心跳
                    this.send(JSON.stringify({ pong: json.ping }));
                } else {
                    // 通知所有监听器
                    this.listeners.forEach((callback) => callback(json));
                }
            } catch (e) {
                console.error('Error processing WebSocket message:', e);
            }
        });

        // 监听错误事件
        this.socketTask.onError((err) => {
            console.error('WebSocket error:', err);
        });

        // 监听关闭事件
        this.socketTask.onClose(() => {
            console.log('WebSocket connection closed.');
            this.isConnected = false;
        });
    }

    /**
     * 关闭当前 WebSocket 连接
     * @param {Array} subscriptions - 需要取消订阅的主题
     */
    close(subscriptions = []) {
        if (this.isConnected && this.socketTask) {
            if (subscriptions.length > 0) {
                const unsubscribeMessage = JSON.stringify({
                    unsub: subscriptions,
                });
                this.send(unsubscribeMessage);
            }

            // 关闭当前 WebSocket
            this.socketTask.close({
                success: () => {
                    console.log('WebSocket connection closed successfully.');
                },
                fail: (err) => {
                    console.error('Failed to close WebSocket connection:', err);
                },
            });

            this.isConnected = false;
            this.socketTask = null; // 清除引用
        } else {
            console.warn('WebSocket is not connected or already closed.');
        }
    }

    /**
     * 发送消息
     * @param {string} message - 消息内容
     */
    send(message) {
        if (this.isConnected && this.socketTask) {
            this.socketTask.send({
                data: message,
                success: () => {
                    console.log('Message sent:', message);
                },
                fail: (err) => {
                    console.error('Failed to send message:', err);
                },
            });
        } else {
            console.warn('Cannot send message. WebSocket is not connected.');
        }
    }

    /**
     * 注册消息监听器
     * @param {Function} callback - 回调函数
     */
    onMessage(callback) {
        if (typeof callback === 'function') {
            this.listeners.push(callback);
        }
    }

    /**
     * 清空所有消息监听器
     */
    unsubscribeAll() {
        this.listeners = [];
    }
}

export default WebSocketManager;
